const baseURL = 'http://124.220.108.74/api' // 假设这是你的 API 地址

// 封装一个请求函数，接收路径和请求配置作为参数
// const request = async (path, options = {}) => {
//   let response;
//   try {
//      //如果是GET请求，且有参数提交
//      if(options.method==undefined && options!={}){
//       var url=new URL(`${baseURL}${path}`);
//       url.search=new URLSearchParams(options).toString();
//       response = await fetch(url);
//      } else{
//       response = await fetch(`${baseURL}${path}`,options);
//      }

//     const data = await response.json();
//     if (!response.ok) {
//       throw new Error( '请求失败');
//     }
//     return data;
//   } catch (error) {
//     throw new Error(error.message || '请求失败');
//   }
// };
/**
 * mmthod:get,post
 * url,
 * params  get
 * data    post
 * headers
 * token
 * responseType,json text
 */

const request = async (path, options) => {
  try {
    //1.url
    let url = path.toString().startsWith('http') ? path : `${baseURL}${path}`
    if (options.params != undefined) url += `?${new URLSearchParams(options.params).toString(url)}`
    //2.headers
    const headers = {
      'Content-Type': 'application/json',
      ...options.headers
    }
    //3. token
    if (options.token != undefined) {
      headers.Authorization = options.token
    }
    const response = await fetch(url, {
      method: options.method,
      headers: headers,
      body: options.data != undefined ? JSON.stringify(options.data) : null
    })
    //4.返回类型
    const data = options.responseType == 'text' ? await response.text() : await response.json()
    if (!response.ok) {
      throw new Error('请求错误')
    } else {
      return data
    }
  } catch (err) {
    throw new Error(err.message || '请求错误')
  }
}
export default request
